using AutoMapper;
using B.S.NewMedical.Api.Read.Application.Command.ContentManagement.Patient;
using B.S.NewMedical.Api.Read.DTOS.Patient;
using B.S.NewMedical.Domain.Hospital;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Read.Application.Handler.ContentManagement.Patient
{
    /// <summary>
    /// 根据患者ID获取患者信息处理器
    /// </summary>
    public class GetPatientByIdHandler : IRequestHandler<GetPatientByIdCommand, ApiResult<PatientDisplayDto>>
    {
        private readonly IBaseRepository<PatientModel> _patientRepository;
        private readonly ILogger<GetPatientByIdHandler> _logger;
        private readonly IMapper _mapper;

        public GetPatientByIdHandler(
            IBaseRepository<PatientModel> patientRepository,
            ILogger<GetPatientByIdHandler> logger,
            IMapper mapper)
        {
            _patientRepository = patientRepository ?? throw new ArgumentNullException(nameof(patientRepository));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
            _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
        }

        /// <summary>
        /// 处理根据患者ID获取患者信息请求
        /// </summary>
        public async Task<ApiResult<PatientDisplayDto>> Handle(GetPatientByIdCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始查询患者详情，患者ID：{PatientId}", request.PatientId);

                // 查询患者信息
                var patient = await _patientRepository.GetValue(request.PatientId);

                if (patient == null || patient.IsDeleted)
                {
                    _logger.LogWarning("患者不存在或已被删除，患者ID：{PatientId}", request.PatientId);
                    return new ApiResult<PatientDisplayDto>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "患者不存在或已被删除"
                    };
                }

                // 映射为DTO
                var patientDto = _mapper.Map<PatientDisplayDto>(patient);

                _logger.LogInformation("查询患者详情成功，患者姓名：{PatientName}", patientDto.Name);

                return new ApiResult<PatientDisplayDto>
                {
                    Code = ApiEnum.Success,
                    Msg = "查询成功",
                    Data = patientDto
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询患者详情时发生错误，患者ID：{PatientId}", request.PatientId);
                return new ApiResult<PatientDisplayDto>
                {
                    Code = ApiEnum.Error,
                    Msg = "查询失败"
                };
            }
        }
    }
}